package encaps.logging;

import encaps.utils.EntityUtil;
import java.util.Date;
import javax.ejb.CreateException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.NamingException;

public class Logger implements MessageDrivenBean, MessageListener {

    public static final String ACTION = "action";
    public static final String USER_ID = "user_id";
    public static final String USER_NAME = "user_name";
    public static final String TIME = "time";
    public static final String ENTITY_TYPE = "entity_type";
    public static final String ENTITY_ID = "entity_id";
    public static final String ENTITY_NAME = "entity_name";
    private MessageDrivenContext context;

    public void setMessageDrivenContext(MessageDrivenContext aContext) {
        context = aContext;
    }

    public void ejbCreate() {
    }

    public void ejbRemove() {
    }

    public void onMessage(Message aMessage) {
        if (!(aMessage instanceof MapMessage)) {
            System.out.println("Unsupported message type. MapMessage required");
            return;
        }
        MapMessage mapMessage = (MapMessage) aMessage;

        LogLocalHome lhome = null;
        LogLocal p = null;
        try {
            lhome = EntityUtil.getLogHome();
            String action = mapMessage.getString(ACTION);
            Long user_id = mapMessage.getLong(USER_ID);
            String user_name = mapMessage.getString(USER_NAME);
            Long time = mapMessage.getLong(TIME);
            String entity_type = mapMessage.getString(ENTITY_TYPE);
            Long entity_id = mapMessage.getLong(ENTITY_ID);
            String entity_name = mapMessage.getString(ENTITY_NAME);
            p = lhome.create(action, user_id, user_name, new Date(time), entity_type, entity_id, entity_name);
        } catch (NamingException ex) {
            //System.out.println("Error looking up log");
        } catch (JMSException ex) {
            //System.out.println("Error in received message");
        } catch (CreateException ex) {
            //System.out.println("Error in received message");
            //ex.printStackTrace();
        }
    }
}
